<template>
  <div class="home-contain">
    <div class="section">
      <div class="home-header">
        <div class="text1">会员列表</div>
        <div class="header-right">
          <el-input
            v-model="data.keyWords"
            style="width: 328px; height: 32px"
            placeholder="输入名称/手机号搜索"
            clearable
          >
            <template #suffix>
              <el-icon @click="search" class="search"><Search /></el-icon>
            </template>
          </el-input>
          <div class="createVipBtn" @click="handleEdit('add')">
            <el-icon color="#ffffff" size="16"><Plus /></el-icon>
            <span>创建会员</span>
          </div>
        </div>
      </div>

      <div class="home-body">
        <el-table :data="data.tableData" style="width: 100%; border-radius: 8px">
          <el-table-column prop="id" label="会员号" width="160" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column label="性别" width="180">
            <template #default="scope">
              {{ scope.row.sex == 1 ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="birth1" label="年龄" width="120" />
          <el-table-column prop="phone" label="手机号" width="160" />
          <el-table-column prop="address" label="登记门店" width="160" />

          <el-table-column label="操作" width="240">
            <template #default="scope">
              <div class="setting">
                <div class="text1" @click="collection(scope.row)">登记采集</div>
                <template v-if="scope.row.frequency1.length > 0">
                  <div class="text2"></div>
                  <div class="text3" @click="seeResult(scope.row)">
                    查看报告（{{ scope.row.frequency1.length }}）
                  </div>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column>
            <template #default="scope">
              <el-icon :size="20" style="cursor: pointer" @click="handleEdit('edit', scope.$index)">
                <Edit />
              </el-icon>
              <!-- <el-icon :size="20" style="cursor: pointer" @click="handleDelete(scope.$index)">
                <Delete />
              </el-icon> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="home-footer">
        <el-pagination
          v-model:current-page="data.currentPage"
          v-model:page-size="data.pageSize"
          :page-sizes="[10, 15, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <!-- 新增编辑会员 -->
  <el-dialog v-model="data.vipDia" class="logoutDia" :close-on-click-modal="false">
    <div class="home-dia-contain">
      <div class="dia-header">
        <div></div>
        <div class="text1">{{ data.vipUuid ? '编辑' : '创建' }}会员</div>
        <el-icon class="el-close" @click="closeVpi"><Close /></el-icon>
      </div>
      <div class="dia-body">
        <div class="dia-label">姓名<span>*</span></div>

        <el-input
          style="width: 360px; height: 38px; margin-bottom: 20px"
          placeholder="输入姓名"
          v-model="data.vipInfo.name"
          clearable
        >
        </el-input>

        <div class="dia-label">性别<span>*</span></div>
        <el-radio-group v-model="data.vipInfo.sex" class="home-radio" style="margin-bottom: 12px">
          <el-radio :value="1">男</el-radio>
          <el-radio :value="2">女</el-radio>
        </el-radio-group>
        <div class="dia-label">年龄<span>*</span></div>
        <el-date-picker
          style="width: 360px; height: 38px; margin-bottom: 20px"
          v-model="data.vipInfo.birth"
          type="date"
          placeholder="请选择年龄"
          format="YYYY-MM-DD"
          value-format="YYYY/MM/DD"
          :size="size"
          :default-value="new Date(1980, 1, 1)"
        />
        <!-- <el-input
          style="width: 360px; height: 38px; margin-bottom: 20px"
          placeholder="输入年龄"
          clearable
          v-model="data.vipInfo.birth"
        >
        </el-input> -->
        <div class="dia-label">登记门店<span>*</span></div>
        <el-select
          v-model="data.vipInfo.address"
          filterable
          placeholder="选择户籍"
          style="width: 360px; height: 38px; margin-bottom: 12px"
        >
          <el-option
            v-for="(item, index) in data.options"
            :key="index"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
        <div class="dia-label">手机号<span>*</span></div>
        <el-input
          style="width: 360px; height: 38px; margin-bottom: 20px"
          placeholder="输入手机号"
          clearable
          v-model="data.vipInfo.phone"
        >
        </el-input>
        <div class="dia-buttons">
          <div class="concelBtn1" @click="closeVpi">取消</div>
          <div class="confirmBtn1" @click="confirmVip">确定</div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup name="home">
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
const router = useRouter()
// 初始化数据
let data = reactive({
  keyWords: '', //关键字

  currentPage: 1,
  pageSize: 10,
  total: 300,
  tableData: [], //table数据
  vipDia: false, //新增编辑会员dia控制器
  vipUuid: '',
  vipInfo: {
    name: '',
    sex: '',
    birth: '',
    address: '',
    phone: ''
  },
  options: [
    {
      value: '门店1'
    },
    {
      value: '门店2'
    },
    {
      value: '门店3'
    },
    {
      value: '门店4'
    }
  ]
})

const getUserList = async () => {
  const res = await window.electron.ipcRenderer.invoke('user-get-userList', {
    keyWords: data.keyWords
  })

  res.list.forEach((el) => {
    el.birth1 = dayjs().diff(el.birth, 'years')
    el.birth2 = dayjs(el.birth).format('YYYY-MM-DD')
    el.frequency1 = el.frequency.filter((item) => item.status == 1)
  })
  // console.log(res)
  // res.list.sort((a, b) => b.updatetime - a.updatetime)
  data.tableData = res.list
  data.total = res.total
}
getUserList()

// 搜索
const search = () => {
  getUserList()
}
// 采集
const collection = async (row) => {
  //  确定此用户没有未填写的报告
  let frequencyId = '',
    flag = false
  if (row.frequency.length == 0) {
    flag = true
  } else {
    row.frequency.forEach((el) => {
      if (el.status == '2') {
        frequencyId = el.id
      }
    })
    if (frequencyId === '') {
      flag = true
    }
  }
  // 创建新的
  if (flag) {
    const res = await window.electron.ipcRenderer.invoke('frequency-add', {
      userId: row.id,
      status: '2',
      createtime: (dayjs().valueOf() / 1000).toFixed(0),
      updatetime: (dayjs().valueOf() / 1000).toFixed(0)
    })

    frequencyId = res.id
  }
  // 更新时间
  else {
    let res = window.electron.ipcRenderer.invoke('frequency-update', {
      id: frequencyId,
      data: {
        updatetime: (dayjs().valueOf() / 1000).toFixed(0)
      }
    })
  }
  router.push({
    name: 'questionnaire',
    query: {
      id: frequencyId
    }
  })
}
// 查看报告
const seeResult = (row) => {
  router.push({
    name: 'result',
    query: {
      id: row.frequency1[0].id
    }
  })
}
// 删除
const handleDelete = async (index) => {
  const res = await window.electron.ipcRenderer.invoke('user-delete-user', data.tableData[index].id)
  if (res) {
    getUserList()
  }
}
// 新增 / 编辑
const handleEdit = (type, index) => {
  if (type == 'add') {
    data.vipInfo = {
      name: '张世林',
      sex: 1,
      birth: '1980/01/01',
      address: '门店1',
      phone: '15660091592'
      // name: '',
      // sex: '',
      // birth: '',
      // address: '',
      // phone: ''
    }
    data.vipUuid = ''
    data.vipDia = true
    return
  }
  data.vipUuid = data.tableData[index].id
  data.vipInfo = data.tableData[index]
  data.vipDia = true
}
// 取消 新增 / 编辑 会员
const closeVpi = () => {
  ElMessageBox.confirm('确定关闭取消吗?', {
    cancelButtonText: '确定',
    confirmButtonText: '确定'
  })
    .then(() => {
      data.vipDia = false
      done()
    })
    .catch(() => {})
}
// 确定 新增 / 编辑 会员
const confirmVip = async () => {
  if (!data.vipInfo.name) {
    return window.showMessage({
      type: 'error',
      message: '请输入姓名'
    })
  }
  if (!data.vipInfo.sex) {
    return window.showMessage({
      type: 'error',
      message: '请选择性别'
    })
  }
  if (!data.vipInfo.name) {
    return window.showMessage({
      type: 'error',
      message: '请输入姓名'
    })
  }
  if (!data.vipInfo.name) {
    return window.showMessage({
      type: 'error',
      message: '请输入姓名'
    })
  }
  if (!data.vipInfo.name) {
    return window.showMessage({
      type: 'error',
      message: '请输入姓名'
    })
  }
  let res
  if (!data.vipUuid) {
    res = await window.electron.ipcRenderer.invoke('user-add-user', {
      ...data.vipInfo,
      createtime: (dayjs().valueOf() / 1000).toFixed(0),
      updatetime: (dayjs().valueOf() / 1000).toFixed(0)
    })
  } else {
    res = await window.electron.ipcRenderer.invoke('user-update-user', data.vipUuid, {
      ...data.vipInfo,
      updatetime: (dayjs().valueOf() / 1000).toFixed(0)
    })
  }

  if (res) {
    getUserList()
  }

  data.vipDia = false
}
// 分页器size改变
const handleSizeChange = () => {
  setTimeout(() => {}, 200)
}
// 分页器currentPage改变
const handleCurrentChange = () => {}
</script>

<style lang="less" scoped>
.home-contain {
  padding: 16px 24px;
  height: calc(100% - 50px);
  overflow: scroll;
}

.section {
  padding: 12px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  min-height: 100%;
}
.home-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;

  .text1 {
    font-family: AlibabaPuHuiTi_2_85_Bold;
    font-size: 20px;
    color: #333333;
    letter-spacing: 0;
    font-weight: 700;
  }
  .header-right {
    display: flex;
    align-items: center;
    .createVipBtn {
      margin-left: 20px;
    }
  }
}
.search {
  cursor: pointer;
}
.setting {
  display: flex;
  align-items: center;
  font-size: 15px;
  font-weight: 500;
  font-family: AlibabaPuHuiTi_2_65_Medium;
  .text1 {
    color: #31bab5;
    cursor: pointer;
  }
  .text2 {
    width: 1px;
    height: 16px;
    background: #dcdfe6;
    margin: 0 10px;
  }
  .text3 {
    color: #1a9bff;
    cursor: pointer;
  }
}
.home-dia-contain {
  width: 420px;
  .dia-header {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px 10px;
    border-bottom: 1px solid #dcdfe6;
    .text1 {
      font-size: 20px;
      color: #333333;
      letter-spacing: 0;
      line-height: 17px;
      font-weight: 900;
    }
    .el-close {
      position: absolute;
      top: 50%;
      right: 10px;
      transform: translateY(-50%);
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #eceded;
      border-radius: 50%;
      color: #000;
      font-size: 20px;
      font-weight: 900;
      cursor: pointer;
    }
  }
  .dia-body {
    padding: 18px 30px 20px;
    .dia-label {
      font-family: AlibabaPuHuiTi_2_65_Medium;
      font-size: 15px;
      color: #333333;
      letter-spacing: 0;
      line-height: 14px;
      font-weight: 900;
      margin-bottom: 10px;
      span {
        color: #ff4d4f;
      }
    }
    .dia-buttons {
      display: flex;
      align-items: center;
      justify-content: center;
      .concelBtn1 {
        margin-right: 12px;
      }
    }
  }
}
.home-footer {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
</style>
